package com.yeeyk.shell.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

/**
 * Created by zhangjuntao on 2017/4/7.
 */
@Component
public class CreateBeanDefinitionService implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void initBean()throws Exception{
        handlerBeanDefinition(BeanDefinnitBean.class,null);
    }


    public void handlerBeanDefinition(Class c,Class parent)throws Exception{
        BeanDefinitionRegistry beanRegistry = (BeanDefinitionRegistry) applicationContext;
        String className = c.getName();
        String beanName = className.length() >= 2 ? className.substring(0,1).toLowerCase()+className.substring(2)
                : ( className.length() >= 1 ? className.substring(0,1).toLowerCase() : null);
        AbstractBeanDefinition abstractBeanDefinition = BeanDefinitionReaderUtils.createBeanDefinition( parent != null ? parent.getName() : null , className, this.getClass().getClassLoader());
        beanRegistry.registerBeanDefinition(beanName,abstractBeanDefinition );
    }




}
